# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django import forms
from multi_media_to_text.speech_model import ModelSpeech
from multi_media_to_text.speech_model_zoo import SpeechModel251
from multi_media_to_text.speech_features import Spectrogram
from multi_media_to_text.LanguageModel2 import ModelLanguage

import subprocess
import json
import requests
import os


os.environ["CUDA_VISIBLE_DEVICES"] = "0"
AUDIO_LENGTH = 1600
AUDIO_FEATURE_LENGTH = 200
CHANNELS = 1
# 默认输出的拼音的表示大小是1428，即1427个拼音+1个空白块
OUTPUT_SIZE = 1428


class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()


def multi_media_to_text(request):
    return render(request, "home.html", {})


def single_multi_media_to_text(request):
    return render(request, "single_home.html", {})


def batch_image_to_text(request):
    return render(request, "batch_image_to_text.html", {})


def batch_video_to_text(request):
    return render(request, "batch_video_to_text.html", {})


def batch_audio_to_text(request):
    return render(request, "batch_audio_to_text.html", {})


def image_to_text(request):
    return render(request, "image_to_text.html", {})


def video_to_text(request):
    return render(request, "video_to_text.html", {})


def audio_to_text(request):
    return render(request, "audio_to_text.html", {})


@csrf_exempt
def single_image_to_text(request):
    sum_result = ''
    length = request.FILES.__len__()
    for i in range(length):
        image_file = request.FILES.get('files[' + str(i) + ']')
        file = open('/Users/zhangjian/Downloads/text/' + image_file.name, 'wb')
        for chunk in image_file.chunks():
            file.write(chunk)
        file.close()
        url = 'http://localhost:8081/convert/singleImage2Text'
        data = {
            'filePath': '/Users/zhangjian/Downloads/text/' + image_file.name
        }
        headers = {'Content-Type': 'application/json'}
        result = requests.post(url, headers=headers, data=json.dumps(data))
        sum_result += result.text + '\n'
        return HttpResponse(sum_result)


@csrf_exempt
def image2text(request):
    sum_result = ''
    length = request.FILES.__len__()
    for i in range(length):
        image_file = request.FILES.get('files[' + str(i) + ']')
        file = open('/Users/zhangjian/Downloads/text/' + image_file.name, 'wb')
        for chunk in image_file.chunks():
            file.write(chunk)
        file.close()
        url = 'http://localhost:8081/convert/Image2Text'
        data = {
            'filePath': '/Users/zhangjian/Downloads/text/' + image_file.name
        }
        headers = {'Content-Type': 'application/json'}
        result = requests.post(url, headers=headers, data=json.dumps(data))
        sum_result += result.text + '\n'
    return HttpResponse(sum_result)


@csrf_exempt
def video2text(request):
    sum_result = ''
    length = request.FILES.__len__()
    for i in range(length):
        video_file = request.FILES.get('files[' + str(i) + ']')
        source_file = '/Users/zhangjian/Downloads/text/' + video_file.name
        file = open(source_file, 'wb+')
        for chunk in video_file.chunks():
            file.write(chunk)
        file.close()

        target_file_name = str(video_file.name.split('.')[0])
        target_file_path = '/Users/zhangjian/Downloads/text/' + target_file_name
        target_file = target_file_path + '.wav'
        command = 'ffmpeg -i ' + source_file + ' -ar 16000 ' + target_file
        os.system(command)

        target_file_path, result = cut_audio_to_spell(target_file, target_file_path, target_file_name)
        os.remove(source_file)
        os.remove(target_file)
        content = video_file.name + '转换成功，文件存储在 ' + target_file_path + '\n'
        sum_result += content
    return HttpResponse(sum_result)


@csrf_exempt
def single_video_to_text(request):
    length = request.FILES.__len__()
    for i in range(length):
        video_file = request.FILES.get('files[' + str(i) + ']')
        source_file = '/Users/zhangjian/Downloads/text/' + video_file.name
        file = open(source_file, 'wb+')
        for chunk in video_file.chunks():
            file.write(chunk)
        file.close()

        target_file_name = str(video_file.name.split('.')[0])
        target_file_path = '/Users/zhangjian/Downloads/text/' + target_file_name
        target_file = target_file_path + '.wav'
        command = 'ffmpeg -i ' + source_file + ' -ar 16000 ' + target_file
        os.system(command)

        target_file_path, result = cut_audio_to_spell(target_file, target_file_path, target_file_name)
        os.remove(source_file)
        os.remove(target_file)
    return HttpResponse(result)


# 开始进行视频分割
def cut_audio_to_spell(target_file, target_file_path, target_file_name):
    file_length = get_video_length(target_file)
    result = ''
    if file_length > 5:
        is_exists = os.path.exists(target_file_path)
        if not is_exists:
            os.mkdir(target_file_path)
        cut = 'ffmpeg -i ' + target_file + ' -f segment -segment_time 5 -c copy -ar 16000 ' + target_file_path + '/' + target_file_name + '%03d.wav'
        os.system(cut)
        files = os.listdir(target_file_path)
        files.sort(key=lambda x: int(x.replace(target_file_name, "").split('.')[0]))
        for file in files:
            f = open(target_file_path + "/" + file, 'rb')
            content = wave_to_text(f)
            result += content
        del_dir(target_file_path)
    else:
        content = wave_to_text(target_file)
        result += content
        os.remove(target_file)
    target_file_path = '/Users/zhangjian/Downloads/text/' + target_file_name + '.txt'
    file = open(target_file_path, 'w')
    file.write(str(result))
    file.close()
    return target_file_path, result


def del_dir(file_path):
    if not os.path.exists(file_path):
        return False
    if os.path.isfile(file_path):
        os.remove(file_path)
        return
    for i in os.listdir(file_path):
        t = os.path.join(file_path, i)
        if os.path.isdir(t):
            # 重新调用次方法
            del_dir(t)
        else:
            os.unlink(t)
    # 递归删除目录下面的空文件夹
    os.removedirs(file_path)


def get_video_length(input_video):
    result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_video], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return float(result.stdout)


@csrf_exempt
def audio2text(request):
    sum_result = ''
    length = request.FILES.__len__()
    for i in range(length):
        audio_file = request.FILES.get('files[' + str(i) + ']')
        source_file = '/Users/zhangjian/Downloads/text/' + audio_file.name
        file = open(source_file, 'wb+')
        for chunk in audio_file.chunks():
            file.write(chunk)
        file.close()
        target_file_name = str(audio_file.name.split('.')[0])
        target_file_path = '/Users/zhangjian/Downloads/text/' + target_file_name
        target_file = target_file_path + '.wav'
        target_file_path, result = cut_audio_to_spell(target_file, target_file_path, target_file_name)
        content = audio_file.name + '转换成功，文件存储在 ' + target_file_path + '\n'
        sum_result += content
    return HttpResponse(sum_result)


@csrf_exempt
def single_audio_to_text(request):
    length = request.FILES.__len__()
    for i in range(length):
        audio_file = request.FILES.get('files[' + str(i) + ']')
        source_file = '/Users/zhangjian/Downloads/text/' + audio_file.name
        file = open(source_file, 'wb+')
        for chunk in audio_file.chunks():
            file.write(chunk)
        file.close()
        target_file_name = str(audio_file.name.split('.')[0])
        target_file_path = '/Users/zhangjian/Downloads/text/' + target_file_name
        target_file = target_file_path + '.wav'
        target_file_path, result = cut_audio_to_spell(target_file, target_file_path, target_file_name)
    return HttpResponse(result)


def wave_to_text(audio_file):
    sm251 = SpeechModel251(
        input_shape=(AUDIO_LENGTH, AUDIO_FEATURE_LENGTH, CHANNELS),
        output_size=OUTPUT_SIZE
    )
    feat = Spectrogram()
    ms = ModelSpeech(sm251, feat, max_label_length=64)

    ms.load_model('multi_media_to_text/' + sm251.get_model_name() + '.model.h5')
    res = ms.recognize_speech_from_file(audio_file)
    print('*[提示] 声学模型语音识别结果：\n', res)

    ml = ModelLanguage('model_language')
    ml.LoadModel()
    str_pinyin = res
    result = ml.SpeechToText(str_pinyin)
    return result

